package com.serialcommunication.helper;

import static com.serialcommunication.constants.ProtocolConstants.*;
import static com.serialcommunication.helper.ActionUtil.*;
import static com.serialcommunication.helper.ByteUtil.*;
import org.apache.soap.encoding.Hex;

import com.serialcommunication.enums.Engine;
import com.serialcommunication.enums.Sign;
import com.serialcommunication.interfaces.IBaseComponent;
import com.serialcommunication.interfaces.ITransmitComponent;
import com.serialcommunication.model.DynamicAction;

/**
 * Class to generate 8-bytes-long message array
 * 
 * @author Alex
 * 
 */
public class MessageFactory {

	public byte[] generateMessage(ITransmitComponent comp) {
		return generateMessage(comp, Sign.PLUS);
	}

	/**
	 * Generates the message array
	 * 
	 * @param id
	 *            for engie one to three
	 * @param pActionName
	 *            indicating command
	 * @param pValue
	 *            desired value
	 * @return
	 */
	public byte[] generateMessage(ITransmitComponent comp,  Sign pSign) {
		byte[] message = new byte[8];

		/* BYTE 1 ------------------------------------ */
		message[0] = hexToByte(START_HEX);

		/* BYTE 2 ------------------------------------- */
		if (comp.getEngine().equals(Engine.ENGINE_1)) {
			message[1] = hexToByte(ENGINE_1_HEX);
		} else if (comp.getEngine().equals(Engine.ENGINE_2)) {
			message[1] = hexToByte(ENGINE_2_HEX);
		} else if (comp.getEngine().equals(Engine.ENGINE_3)) {
			message[1] = hexToByte(ENGINE_3_HEX);
		}

		/* BYTE 3 ------------------------------------ */
		message[2] = hexToByte(HexUtil.generateHexForOneByte(comp.getAction().getCommand()));

		/* BYTE 4 - 7 (Payload) -------------------- */
		if (comp.isBinary()) {
			byte[] payload = ByteUtil.setSigleBitOfPayloadBytes(comp.getAction().getBitNumberOrNumberOfUsedBits());
			message[3] = payload[3];
			message[4] = payload[2];
			message[5] = payload[1];
			message[6] = payload[0];
		} else {
			String payloadString = preparePayloadString(comp.getValue());
			String[] payloadArray = payloadString.split(" ");
			if (pSign.equals(Sign.MINUS)) {
				message[3] = modifyLargestBit(hexToByte(HexUtil.generateHexForOneByte(payloadArray[0])));
			} else {
				message[3] = hexToByte(new Hex(payloadArray[0]));
			}
			message[4] = ByteUtil.hexToByte(HexUtil.generateHexForOneByte(payloadArray[1]));
			message[5] = ByteUtil.hexToByte(HexUtil.generateHexForOneByte(payloadArray[2]));
			message[6] = ByteUtil.hexToByte(HexUtil.generateHexForOneByte(payloadArray[3]));
		}
		
		message[7] = hexToByte(END_HEX);

		return message;
	}

	private String preparePayloadString(String payload) {
		String[] payloadArray = payload.split(" ");
		if (payloadArray.length == 1) {
			payload = "00 00 " + payload;
		} else if (payloadArray.length == 2) {
			payload = "00 " + payload;
		}
		return "00 " + payload; // now we have 4 bytes of payload...
	}
}
